// 公共工具
export class commonUtils {

  /**
   *json转换为map
   */
  static _jsonToMap(jsonStr){
    return this._objToStrMap(JSON.parse(jsonStr));
  }

  static _objToStrMap(obj){
    let strMap = new Map();
    for (let k of Object.keys(obj)) {
      strMap.set(k,obj[k]);
    }
    return strMap;
  }

  // uuid
  static guid() {
    function S4() {
      return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    }
    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
  }

  static checkPhone(phone){
    if (phone) {
      if(!(/^1[3456789]\d{9}$/.test(phone))){
        return false;
      }
      return true;
    }
    return false;
  }

  // 日期格式化
  static parseTime(time, pattern) {
    if (arguments.length === 0 || !time) {
      return null
    }
    const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
    let date
    if (typeof time === 'object') {
      date = time
    } else {
      if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
        time = parseInt(time)
      } else if (typeof time === 'string') {
        time = time.replace(new RegExp(/-/gm), '/');
      }
      if ((typeof time === 'number') && (time.toString().length === 10)) {
        time = time * 1000
      }
      date = new Date(time)
    }
    const formatObj = {
      y: date.getFullYear(),
      m: date.getMonth() + 1,
      d: date.getDate(),
      h: date.getHours(),
      i: date.getMinutes(),
      s: date.getSeconds(),
      a: date.getDay()
    }
    const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
      let value = formatObj[key]
      // Note: getDay() returns 0 on Sunday
      if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
      if (result.length > 0 && value < 10) {
        value = '0' + value
      }
      return value || 0
    })
    return time_str
  }

  // 获取文件后缀名
  static getFileSuffix(fileName) {
    return fileName.split('.').pop().toLowerCase();
  }

  // 验证日期是否大于当前时间
  static verifyBeforeCurrentTime(date) {
    var currentDate = this.parseTime(new Date(), '{y}-{m}-{d}');
    if (date >= currentDate) {
      return true;
    }
    return false;
  }

  // 验证日期是否大于当前时间
  static verifyDateSize(date1, date2) {
    var datea = this.parseTime(date1, '{y}-{m}-{d} {h}:{i}:{s}');
    var dateb = this.parseTime(date2, '{y}-{m}-{d} {h}:{i}:{s}');
    if (datea >= dateb) {
      return true;
    }
    return false;
  }

  // 日期 距离当前时间有多少天
  static getDaysCurrent(date) {

    const startDate = Date.parse(date);
    const endDate = Date.parse(new Date());
    const days = (startDate - endDate) / (1*24*60*60*1000);
    if (days <= 0) {
      return '<span style="color: brown">今日到期</span>'
    }
    if (days.toFixed(0) && days.toFixed(0) <= 30) {
      return '<span style="color: orange;" title="请注意到期">' + days.toFixed(0) + '天</span>'
    }  else {
      return '<span style="color: darkgreen">' + days.toFixed(0) + '天</span>'
    }
  }

   static parseJsonToStr(text) {
    if (text) {
      let map = JSON.parse(text)
      return this.getMapKeyVale(map);
    }
  }

  //
  static getMapKeyVale(mapObject) {
    let str = ''
    for (var key in mapObject) {
      str += key + ': ' + mapObject[key] + '; '
    }
    return str;
  }

  // 中国标准时间 定义格式化函数：
  static handleStandardTime (time, format) {
    if (time === null || time === undefined || time === "") {
      return "";
    }
    var t = new Date(time);
    var tf = function (i) {
      return (i < 10 ? '0' : '') + i
    };
    return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function (a) {
      switch (a) {
        case 'yyyy':
          return tf(t.getFullYear());
          //eslint-disable-next-line no-unreachable
          break;
        case 'MM':
          return tf(t.getMonth() + 1);
          //eslint-disable-next-line no-unreachable
          break;
        case 'mm':
          return tf(t.getMinutes());
          //eslint-disable-next-line no-unreachable
          break;
        case 'dd':
          return tf(t.getDate());
          //eslint-disable-next-line no-unreachable
          break;
        case 'HH':
          return tf(t.getHours());
          //eslint-disable-next-line no-unreachable
          break;
        case 'ss':
          return tf(t.getSeconds());
          //eslint-disable-next-line no-unreachable
          break;
      }
    })
  }

  // 日期相减
  static dateDiff (param) {
    // 给日期类对象添加日期差方法，返回日期与diff参数日期的时间差，单位为天
    Date.prototype.diff = function(date){
      return (this.getTime() - date.getTime())/(24 * 60 * 60 * 1000);
    }
    // 构造两个日期
    var now = new Date();
    var date = new Date(param);
    // 调用日期差方搜索法，求得参数日期与系统时间相差的天数
    var diff = date.diff(now);
    return diff;
  }


  // 两个日期相减
  static startDateDiffEndDate (start, end) {
    // 给日期类对象添加日期差方法，返回日期与diff参数日期的时间差，单位为天
    Date.prototype.diff = function(date){
      return (this.getTime() - date.getTime()) / (24 * 60 * 60 * 1000);
    }
    // 构造两个日期
    var startDate = new Date(this.parseTime(start, '{y}-{m}-{d}'));
    var endDate= new Date(this.parseTime(end, '{y}-{m}-{d}'));
    // 调用日期差方搜索法，求得参数日期与系统时间相差的天数
    var diff = startDate.diff(endDate);
    return diff;
  }

  /*
   ** randomWord 产生任意长度随机字母数字组合
   ** randomFlag-是否任意长度 min-任意长度最小位[固定位数] max-任意长度最大位
  */
  static randomWord(randomFlag, min, max){
    var str = "",
      range = min,
      arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

    // 随机产生
    if(randomFlag){
      range = Math.round(Math.random() * (max-min)) + min;
    }
    for(var i=0; i<range; i++){
      var pos = Math.round(Math.random() * (arr.length-1));
      str += arr[pos];
    }
    return str;
  }

  /**
   * 根据类型获取流程状态
   * @param dictType
   * @returns Array
   */
  static getProcessStatusCacheByType(dictType) {
    if (dictType && dictType !== '') {
      return JSON.parse(localStorage.getItem(dictType));
    }
  }

  /**
   * 根据类型和dictCode获取字典值
   * @param dictType
   * @param dictCode
   * @returns String
   */
  static getProcessStatusValueByCode(dictType, dictCode) {
    if (dictType && dictCode) {
      const dictArray = JSON.parse(localStorage.getItem(dictType));
      if (dictArray) {
        for (let i in dictArray) {
          if (dictCode === dictArray[i].dictCode) return dictArray[i];

        }
      }
    }
  }

  // vuetify
  // 创建时间 日期格式化
  static formatDate (date) {
    if (!date) return null
    const [year, month, day] = date.split('-')
    return `${month}/${day}/${year}`
  }
  static parseDate (date) {
    if (!date) return null
    const [month, day, year] = date.split('/')
    return `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`
  }
}
